<template>
  <div class="city">
    <div class="search">
      <input type="text" v-model="keywords" name="" id="" placeholder="请输入城市名或拼音" />
    </div>
    <div class="search-content" ref="content" v-show="keywords">
      <ul>
        <li class="search-item" v-for="item in list" :key="item.id" @click="handleCityClick(item.name)" > {{item.name}}</li>
        <li class="search-item" v-show="length">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
export default {
  name: 'citySearch',
  data () {
    return {
      keywords: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  props: {
    city: Object
  },
  computed: {
    length () {
      return this.list.length < 1
    }
  },
  watch: {
    keywords () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keywords) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (const i in this.city) {
          this.city[i].forEach(value => {
            if (value.spell.indexOf(this.keywords) > -1 ||
            value.name.indexOf(this.keywords) > -1) {
              result.push(value)
            }
            this.list = result
          })
        }
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.content)
  }
}
</script>
<style lang="scss">
@import "~@/assets/css/vertauls";
.city {
  .search {
    height: 60px;
    line-height: 60px;
    background-color: $bgColor;
    padding: 0 10px;
    input {
      box-sizing: border-box;
      width: 100%;
      height: 50px;
      line-height: 50px;
      text-align: center;
      border-radius: 10px;
      font-size: 24px;
      color: #000;
      padding: 0 10px;
    }
  }
  .search-content {
      z-index: 1;
      overflow: hidden;
      position: absolute;
      top: 148px;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #fff;
      .search-item {
        background-color: #fff;
        line-height: 40px;
        color: #333;
        font-size: 18px;
        padding-left: 15px;
        border-bottom: 1px solid #ccc;
      }
    }
}
</style>
